package com.sinosoft.cloud.access.persist;

import com.sinosoft.cloud.access.entity.TranData;
import com.sinosoft.cloud.access.net.AccessControl;
import com.sinosoft.cloud.common.SpringContextUtils;
import com.sinosoft.cloud.mq.MessageQueueProducer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017-12-22.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PersisterServiceImpl implements Persister {

    private final Log logger = LogFactory.getLog(getClass());

    private String accessName;

    /**
     * 创建由spring管理的MQ的消息发送者对象
     */
    MessageQueueProducer producer = SpringContextUtils.getBeanByClass(MessageQueueProducer.class);

    /**
     * 创建由spring管理的读取配置文件对象
     */
    AccessControl accessControl = SpringContextUtils.getBeanByClass(AccessControl.class);

    /**
     * 报文持久化
     *
     * @param msg
     * @param tranData
     */
    @Override
    public void msgPersistent(String msg, TranData tranData, String messageType) {
        Boolean clearTextSwitch = accessControl.getClearTextSwitch();
        logger.info("是否需要明文持久化？" + clearTextSwitch);
        if (clearTextSwitch) {
            /*传输的数据集合*/
            List<String> sendText = new ArrayList<>();
            //银行信息
            sendText.add(accessName);
            //渠道信息
            sendText.add(tranData.getHead().getSourceType());
            //交易编码
            sendText.add(tranData.getHead().getTransCode());
            //原始报文
            sendText.add(msg);
            //交易流水号
            sendText.add(tranData.getHead().getTranNo());
            //报文类型，是原始报文还是返回报文
            sendText.add(messageType);
            producer.send("PlainText", sendText);
            logger.info("已经发送明文持久化消息！");
        }
    }

    @Override
    public void setAccessName(String accessName) {
        this.accessName = accessName;
    }
}
